package com.rc.web.service.impl;

import com.rc.common.properties.MinioProperties;
import com.rc.pojo.vo.file.UploadVO;
import com.rc.web.service.FileService;
import io.minio.ListObjectsArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.Result;
import io.minio.messages.Item;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * Minio文件服务实现类
 * 提供基于Minio的文件上传服务
 */
@Service
@RequiredArgsConstructor
public class MinioFileServiceImpl implements FileService {
    // Minio配置属性
    private final MinioProperties minioProperties;
    // Minio客户端
    private final MinioClient minioClient;

    /**
     * 上传文件到Minio
     * @param file 要上传的文件
     * @return 包含文件访问URL的UploadVO对象
     */
    @Override
    public UploadVO upload(MultipartFile file) {
        try {
            // 检查文件是否为空
            if (file == null || file.getSize() == 0) {
                throw new RuntimeException("文件大小不能为空");
            }

            // 获取文件的Content-Type
            String contentType = file.getContentType();

            // 生成唯一文件名
            String uuid = UUID.randomUUID().toString();
            String originalFilename = file.getOriginalFilename();
            String fileName = uuid + originalFilename.substring(originalFilename.lastIndexOf("."));

            // 构建PutObjectArgs对象
            PutObjectArgs object = PutObjectArgs.builder()
                    .bucket(minioProperties.getBucketName()) // 设置存储桶名称
                    .object(fileName) // 设置对象名称
                    .stream(file.getInputStream(), file.getSize(), -1) // 设置文件流
                    .contentType(contentType) // 设置文件类型
                    .build();

            // 上传文件到Minio
            minioClient.putObject(object);
            String newEndpoint ="https://47.98.129.55";

            // 构建文件访问URL
            String url = String.format("%s/%s/%s", newEndpoint, "images/"+minioProperties.getBucketName(), fileName);
            System.out.println(url);
            
            // 返回包含URL的UploadVO对象
            return UploadVO.builder()
                    .url(url)
                    .build();

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }





    /**
     * 上传海报到指定文件夹
     * @param file 要上传的文件
     * @param folder 目标文件夹路径
     * @return 包含文件访问URL的UploadVO对象
     */
    @Override
    public UploadVO uploadToFolder(MultipartFile file, String folder) {
        try {
            if (file == null || file.getSize() == 0) {
                throw new RuntimeException("文件大小不能为空");
            }

            String contentType = file.getContentType();
            String uuid = UUID.randomUUID().toString();
            String originalFilename = file.getOriginalFilename();
            String fileName = folder + "/" + uuid + originalFilename.substring(originalFilename.lastIndexOf("."));

            PutObjectArgs object = PutObjectArgs.builder()
                    .bucket(minioProperties.getBucketName())
                    .object(fileName)
                    .stream(file.getInputStream(), file.getSize(), -1)
                    .contentType(contentType)
                    .build();

            minioClient.putObject(object);

            String url = String.format("%s/%s/%s", minioProperties.getEndpoint(), minioProperties.getBucketName(), fileName);
            
            return UploadVO.builder()
                    .url(url)
                    .build();

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    @Override
    public List<String> getImagesFromFolder(String folder) {
        try {
            // 确保文件夹路径以/结尾
            if (!folder.endsWith("/")) {
                folder = folder + "/";
            }

            // 获取文件夹下的所有对象
            Iterable<Result<Item>> results = minioClient.listObjects(
                    ListObjectsArgs.builder()
                            .bucket(minioProperties.getBucketName())
                            .prefix(folder)
                            .recursive(false)
                            .build());
            String newEndpoint ="https://47.98.129.55";

            // 构建图片URL列表
            List<String> imageUrls = new ArrayList<>();
            for (Result<Item> result : results) {
                Item item = result.get();
                if (!item.isDir()) {
                    String url = String.format("%s/%s/%s", 
                            newEndpoint,
                            "images/"+minioProperties.getBucketName(),
                            item.objectName());
                    imageUrls.add(url);
                }
            }

            return imageUrls;
        } catch (Exception e) {
            throw new RuntimeException("获取文件夹图片失败", e);
        }
    }
}
